package com.dmgn.serviceimpl;

import java.io.File;
import java.util.Date;
import java.util.Locale;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;

import com.dmgn.bean.Thesis;
import com.dmgn.service.IArchivesService;
import com.dmgn.service.ICSVConverter;

public class CSVImportThesisImpl implements ICSVConverter {

	@Override
	public String batchImport(String fileName) {
		IArchivesService archivesService = new ThesisServiceImpl();
		Thesis thesis = new Thesis();
		String msg = "第";
		try {
		    // 载入Excel文件     
		    WorkbookSettings ws = new WorkbookSettings();
		    ws.setLocale(new Locale("en", "EN"));
		    Workbook wk = Workbook.getWorkbook(new File(fileName), ws);
		    // 从工作簿(workbook)取得每页(sheets)
		    for (int sheet = 0; sheet < 1; sheet++) {
		    	Sheet s = wk.getSheet(sheet);
		        Cell[] row = null;
		        // 从每页(sheet)取得每个区块(Cell)
		        for (int i = 1; i < s.getRows()-2; i++) {
		        	row = s.getRow(i);
		        	if (row.length > 0) {
		        		
		        	    thesis.setWebnumber(row[1].getContents());
		        	    thesis.setIssn(row[2].getContents());
		        	    thesis.setTitle(row[3].getContents());
		        	    thesis.setPublication(row[4].getContents());
		        	    thesis.setVolume(row[5].getContents());
		        	    thesis.setIssue(row[6].getContents());
		        	    thesis.setPublicationdate(row[7].getContents());
		        	    thesis.setGrade(row[8].getContents());
		        	    thesis.setSignaturetype(row[9].getContents());
		        	    thesis.setWordcount(row[10].getContents());
		        	    thesis.setIsthefirst(row[11].getContents());
		        	    thesis.setNotheoriginalpaper(row[13].getContents());
		        	    thesis.setAssessmentyear(row[15].getContents());
		        	    thesis.setRegistrant(row[16].getContents());
		        	    thesis.setFirstauthor(row[17].getContents());
		        	    thesis.setCollaborator(row[18].getContents());
		        	    thesis.setDepartment(row[19].getContents());
		        	    thesis.setArrangement(row[20].getContents());
		        	    thesis.setGradepoint(row[21].getContents());
		        	    thesis.setInstitute(row[22].getContents());
		        	    thesis.setEmployeenumber("100");//number
		        	    thesis.setAuditstatus(0);//row[13]
		        	    thesis.setAuditsuggestion(row[14].getContents());
		        	    Date now = new Date();
		        	    thesis.setUploaddate(now);
		        	    thesis.setUpdatedate(now);
		        	    thesis.setStatus(0);
		        		
		        		if(!archivesService.addArchives(thesis))
		        			msg += i+",";
					}
		        }
			}
			if(!msg.trim().equals("第")){
				msg = msg.substring(0, msg.length()-1) + "行数据上传失败，请检查数据库数据是否已经存在。";
			}else{
				msg = "数据全部上传成功。";
			}    
		} catch (Exception e) {
			msg = "打开excel失败";
			System.err.println(e.toString());
			e.printStackTrace(); 
			
		}
		return msg;
	}

}
